<?php

namespace app\h5api\controller;

use app\common\model\Aftersales;
use app\common\model\CouponReceive;
use app\common\model\Express;
use app\common\model\Notice;
use app\common\model\NoticeUser;
use app\common\model\Order as OrderModel;
use app\common\model\Cart;
use app\common\model\OrderDetail;
use app\common\model\OrderExpress;
use app\common\model\Products;
use app\common\model\ServiceMiddle;
use app\common\model\Shops;
use app\common\service\ServiceAdmin;
use app\common\service\ServiceApi;

class Order extends Base
{
    /**
     * @route('h5/GetOrderList','get')
     * 普通商品和兑换商品订单列表
     */
    public function GetOrderList()
    {
        $OrderModel = new OrderModel();
        $limit = input('get.limit',10);
        $status = input('get.status');
        $order_type = input('get.order_type') ? input('get.order_type') : '';
        $pname = input('get.product_name') ? input('get.product_name') : '';
        $iscomment = input('get.is_comment') ? input('get.is_comment') : '';

        $cond = [
            'user_id' => $this->_userid,
            'order_status' => $status,
            'order_type' => $order_type,
            'product_name' => $pname,
            'is_comment' => $iscomment
        ];


        $data = $OrderModel->shops_order_list($cond, 'o.order_id desc', $this->limit,  false, [
            'o.order_id','o.is_show', 'o.shop_id', 's.shop_name', 'o.pay_amount', 'o.order_status', 'o.is_comment','f.express_name', 'o.pay_status', 'o.express_fee', 's.imagesurl', 'o.order_type', 'o.points'
        ], [
            'detail_id', 'order_id', 'product_id', 'product_name','p_s_id', 'p_s_name', 'cover_url', 'sale_price', 'amount', 'cover_url', 'quantity', 'growth_coin', 'growth_coin_amount'
        ]);
        $data = [
            'data' => $data['data'],
            "total" => $data['page']['total'],
            "per_page" => $data['page']['per_page'],
            "current_page" => $data['page']['current_page'],
            "last_page" => $data['page']['last_page'],
        ];
        $this->result($data, 1, '操作成功');
    }

    /**
     * @route('h5/GetOtherOrders','get')
     * 爱心商品和团餐商品订单列表
     */
    public function GetOtherOrders()
    {
        $OrderModel = new OrderModel();
        $limit = input('get.limit') ? input('get.limit') : 6;
        $status = input('get.status') ? input('get.status') : '';
        $pname = input('get.product_name') ? input('get.product_name') : '';
        $shopname = input('get.shop_name') ? input('get.shop_name') : '';
        $iscomment = input('get.is_comment') ? input('get.is_comment') : '';
        $isuse = input('get.is_use') ? input('get.is_use') : '';
        $classname = input('get.class_name');
        $class_id = '';
        if ($classname == 'love') {
            $class_id = 3;
        } else if ($classname == 'team') {
            $class_id = 4;
        } else {
            $this->result('', -1, '订单类型有误');
        }
        $data = $OrderModel->loveandteam_order_list([
            'user_id' => $this->_userid,
            'order_status' => $status,
            'product_name' => $pname,
            'shop_name' => $shopname,
            'class_id' => $class_id,
            'is_comment' => $iscomment,
            'is_use' => $isuse], 'o.order_id desc', $limit, false, [
            'o.order_id', 'o.shop_id', 's.shop_name', 'o.pay_amount', 'o.order_status', 'o.pay_status', 'o.express_fee', 's.imagesurl', 'o.order_type', 'gr.status as is_use'
        ], [
            'detail_id', 'order_id', 'product_id', 'product_name', 'p_s_name', 'cover_url', 'sale_price', 'amount', 'cover_url', 'quantity'
        ]);
        $data = [
            'data' => $data['data'],
            "total" => $data['page']['total'],
            "per_page" => $data['page']['per_page'],
            "current_page" => $data['page']['current_page'],
            "last_page" => $data['page']['last_page'],
        ];
        $this->result($data, 1, '操作成功');
    }

    /**
     * @route('h5/GetOrderDetail','get')
     * 获取普通商品和兑换商品订单详情
     */
    public function GetOrderDetail()
    {
        $order_id = input('get.order_id');
        $user = $this->GetUserInfo();
        $data = [];
        $orderModel = new OrderModel();
        $afterModel = new Aftersales();

        $where = [
            ['user_id', '=', $user['user_id']],
            ['order_id', '=', $order_id],
            ['order_type', 'in', [1, 2]],
        ];
        $order = $orderModel->getOne($where);
        if (empty($order)) {
            $this->result('', -1, '用户不存在的订单');
        }
        $data['order'] = $order->toArray();

        $after = $afterModel->getOne(['order_id' => $order_id],'content,add_time,update_time');
        if($after){
            $data['order']['after_sales'] = $after;
        }


        $item = 'od.*,s.shop_id';
        $detail = $orderModel->api_order_details($order_id, $item);
//        var_dump($detail);die;
        if (empty($order)) {
            $this->result('', -1, '不存在的订单详情');
        }
        $shop_ids = array_column($detail, 'shop_id');
        $shopModel = new Shops();
//        var_dump($shop_ids);die;
        $shops = $shopModel->get_list(['shop_ids' => $shop_ids], '', 'shop_id,shop_name,shop_phone,address,province,city,area,imagesurl');
        $shops = array_column($shops, null, 'shop_id');
//        var_dump($shops);die;
        foreach ($detail as $value) {
            $detailinfo[$value['shop_id']]['shopinfo'] = $shops[$value['shop_id']];
            $detailinfo[$value['shop_id']]['detailinfo'][] = $value;
        }
        $data['productinfo'] = array_values($detailinfo);
        $this->result($data, 1, '返回信息');
    }

    /**
     * @route('h5/GetOtherDetail','get')
     * 获取爱心餐团餐订单详情
     */
    public function GetOtherDetail()
    {
        $order_id = input('get.order_id');
        $user = $this->GetUserInfo();
        $data = [];
        $orderModel = new OrderModel();
        $where = [
            ['o.user_id', '=', $user['user_id']],
            ['o.order_id', '=', $order_id],
            ['o.order_type', 'in', [3, 4]],
            ['o.is_del', '=', 1]
        ];
        $join = [
            ['ddt_goods_record gr', 'o.order_id = gr.order_id'],
            ['ddt_shops s', 'o.shop_id = s.shop_id']
        ];
        $item = 'o.*,gr.status as is_use,gr.access_code,gr.draw_time,gr.get_time';
        $shopitem = 's.shop_name,s.shop_phone,s.address,s.province,s.city,s.area,s.imagesurl';
        $item .= ',' . $shopitem;
        $order = $orderModel->getJoinOrder($where, $item, $join);
        if (empty($order)) {
            $this->result('', -1, '用户不存在的订单');
        }
        $item = 'od.*';
        $detail = $orderModel->api_order_details($order_id, $item, [['ddt_order o', 'od.order_id = o.order_id']]);
        if (empty($order)) {
            $this->result('', -1, '不存在的订单详情');
        }
        $data = [
            'order' => $order->toArray(),
            'detail' => $detail,
        ];
        $this->result($data, 1, '返回信息');
    }

    /**
     * @route('h5/Settlement','post')
     * 购物车结算
     */
    public function Settlement()
    {
        $ids = input('post.cart_ids');
        $receive_id = input('post.receive_id');
        $CartModel = new Cart();
        $user = $this->GetUserInfo();
        $data = $CartModel->Settlement($user, $ids, $receive_id);
        if (!$data) {
            $this->result([], -1, $CartModel->getError());
//			$this->result([],-1,'商铺或者商品已下架');
        }
        $this->result($data, 1, '操作成功');
    }

    /**
     * @route('h5/UncommonSettlement','post')
     * 非普通商品结算
     */
    public function UncommonSettlement()
    {
        $product_id = input('post.product_id');
        $stock_id = input('post.stock_id');
        $quantity = input('post.quantity');
        $receive_id = input('post.receive_id');
        $OrderModel = new OrderModel();
        $user = $this->GetUserInfo();
        $data = $OrderModel->checkplace($user, $product_id, $stock_id, $quantity, $receive_id);
        if (!$data) {
            $this->result([], -1, $OrderModel->getError());
        }
        $this->result($data, 1, '操作成功');
    }

    /**
     * @route('h5/UserRemind')
     * 用户提醒订单发货
     */
    public function UserRemind()
    {
        $orderModel = new \app\common\model\Order();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operateremind($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

    /**
     * @route('h5/UserCancel')
     * 用户取消订单
     */
    public function UserCancel()
    {
        $orderModel = new \app\common\model\Order();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatecancel($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }

    /**
     * @route('h5/UserSure')
     * 用户确认订单收货
     */
    public function UserSure()
    {
        $orderModel = new \app\common\model\Order();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatesure($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }


    /**
     * @route('h5/userafters')
     * 用户取消售后
     */
    public function UserAfters()
    {
        $orderModel = new \app\common\model\Order();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->userafters($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }


    /**
     * @route('h5/UserDelete')
     * 用户删除订单
     */
    public function UserDelete()
    {
        $orderModel = new \app\common\model\Order();
        $where = [
            'order_id' => input('post.order_id'),
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operatedelete($where);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }


    /**
     * @route('h5/UserComment')
     * 用户获取单个订单详情和订单评价操作
     */
    public function UserComment()
    {
        $orderModel = new OrderModel();
        $orderid = input('get.order_id');
        $detailid = input('get.detail_id');
        $userinfo = $this->GetUserInfo();
        $where = [
            ['o.order_id', '=', $orderid],
            ['o.user_id', '=', $userinfo['user_id']],
            ['od.detail_id', '=', $detailid],
        ];
        $join = [
            ['ddt_orderdetail od', 'o.order_id = od.order_id'],
        ];

        $detail = $orderModel->getJoinOrder($where, 'od.*', $join);
        if (input('post.handle') == 'submit') {
            $params = input('post.');
            //        var_dump($params);die;
            $where = [
                'order_id' => $params['order_id'],
                'detail_id' => $params['detail_id'],
                'user_id' => $this->_userid,
            ];
            $rs = $orderModel->operatecomment($where, $params,9);
            if ($rs === false) {
                $this->result('', -1, $orderModel->getError());
            }
            $this->result('', 1, '操作成功');
        }
        $this->result($detail, 1, '返回');
    }

    /**
     * @route('h5/UserAfterSales')
     * 用户申请售后
     */
    public function UserAfterSales()
    {
        $orderModel = new OrderModel();
        $params = input('post.');
//        var_dump($params);die;
        $where = [
            'order_id' => $params['order_id'],
            'detail_id' => $params['detail_id'],
            'user_id' => $this->_userid,
        ];
        $rs = $orderModel->operateaftersales($where, $params,9);
        if ($rs === false) {
            $this->result('', -1, $orderModel->getError());
        }
        $this->result('', 1, '操作成功');
    }


    /**
     * @route('h5/order/express')
     * 查询快递接口
     */
    public function Express()
    {
        // 订单ID
        $orderId = input('order_id');
        // 物流信息表
        $ServiceAdmin = new ServiceAdmin();
        $orderexpress_data = $ServiceAdmin->CheckExpress($orderId);
        if(!$orderexpress_data){
            $this->result([],-1,$ServiceAdmin->getError());
        }
        $this->result($orderexpress_data,1);
    }


    /**
     * @route('h5/order/countorder','get')
     * 统计不同状态的订单
     */
    public function CountOrder()
    {
        $ServApi = new ServiceApi();
        $rs = $ServApi->GetCountOrder($this->_userid);
        $this->result($rs,1);
    }

    /**
     * @route('h5/order/countnotice','get')
     * 统计消息通知
     */
    public function CountNotice()
    {
        $NoticeModel = new Notice();
        $NoticeUserModel = new NoticeUser();

        $where[] = ['user_id', 'in',"0,".$this->_userid];
        $rs_data = $NoticeModel->where($where)->field('id')->select()->toArray();

        $rs_data = array_column($rs_data,'id');
        $num = 0;
        foreach ($rs_data as $val){
            $rs = $NoticeUserModel->getOne(['user_id' => $this->_userid, 'notice_id' => $val],'id');
            if(!$rs){
                $num += 1;
            }
        }
        $this->result($num,1);
    }



}
